package vip.dexian.admin.security.handler;

import cn.hutool.http.HttpStatus;
import vip.dexian.common.Message;
import vip.dexian.common.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 权限不足，拒绝访问
 *
 * @author 挺好的 2023年06月06日 11:18
 */
@Component ("simpleAccessDeniedHandler")
@Slf4j
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {

    /***
     * 没有权限
     * @param request
     * {@link HttpServletRequest}
     * @param response
     * {@link HttpServletResponse}
     * @param accessDeniedException
     * 异常信息 。{@link org.springframework.security.access.AccessDeniedException}
     * @throws java.io.IOException
     * @throws ServletException
     */
    @Override
    public void handle (HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {

        response.setStatus(HttpStatus.HTTP_FORBIDDEN);

        log.debug("accessDeniedException", accessDeniedException.getMessage());

        // 如果不是ajax请求
        if (!WebUtils.isAjaxRequest(request)) {
            response.sendRedirect("/error/403");
            return;
        }

        WebUtils.responseMessage(response, Message.error(HttpStatus.HTTP_FORBIDDEN));
    }
}
